//
//  ViewController.m
//  Test
//
//  Created by hxh on 2021/6/22.
//

#import "ViewController.h"
#import "ListViewController.h"
@interface ViewController ()<UITextViewDelegate>
@property (nonatomic,strong)UITextView *textView;

@property (nonatomic,assign)NSRange lastRange;

@property (nonatomic,strong)NSMutableDictionary *dict;

@end

@implementation ViewController

- (NSMutableDictionary *)dict{
    if (!_dict) {
        _dict = [NSMutableDictionary dictionary];
    }
    return _dict;
}

- (void)viewDidLoad {
    [super viewDidLoad];


    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 100, 300, 300)];
    self.textView.backgroundColor = [UIColor yellowColor];
    self.textView.delegate = self;
    [self.view addSubview:self.textView];
    
    // Do any additional setup after loading the view.
        
}
- (void)btnMethod{
    [self.view endEditing:YES];
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    // 获取文字改变前的光标的位置
    self.lastRange = textView.selectedRange;
    
    // 处理页面跳转
    if ([text isEqualToString:@"@"]) {
        
        [self.view endEditing:YES];
        
        ListViewController *list = [[ListViewController alloc]init];
        [self presentViewController:list animated:YES completion:nil];
        list.modalPresentationStyle = UIModalPresentationFullScreen;
        
        list.showPerson = ^(NSString *name) {
            // 获取dangqiantextView的坐标
            NSRange selectRange = textView.selectedRange;
            NSInteger realLength = textView.text.length;
            if (realLength + name.length <= 20) {
                
                self.lastRange = selectRange;
                // 设置变化后的光标位置
                NSRange changeRange = NSMakeRange(selectRange.location + name.length, 0);
                
                // 判断插入的位置是否有多选内容
                if (selectRange.length > 0) {
                    NSString *text = [self.textView.text substringWithRange:selectRange];
                    NSString *content = [self.textView.text stringByReplacingOccurrencesOfString:text withString:@"" options:0 range:selectRange];
                    NSMutableString *resultStr = [NSMutableString stringWithString:content];
                    [resultStr insertString:[NSString stringWithFormat:@"%@",name] atIndex:selectRange.location];
                    self.textView.text = resultStr;
                    
                }else{
                    NSString *headText = [self.textView.text substringToIndex:selectRange.location]; //光标前的文本
                    NSString *tailText = [self.textView.text substringFromIndex:selectRange.location];//光标后的文本
                    NSString *str = [NSString stringWithFormat:@"%@%@%@",headText,name,tailText];
                    self.textView.text = str;
                }
                
                self.textView.selectedRange = changeRange;
                
                // 结算两点光标的位置之差
                NSInteger index = changeRange.location - NSMaxRange(self.lastRange);
                // 结果放入字典保存
                NSMutableDictionary *result = [NSMutableDictionary dictionary];
                // 基础
                NSInteger lastIndex = self.lastRange.location;
                // 遍历字典中光标的位置是否需要进行移位或者取消高亮
                [self.dict enumerateKeysAndObjectsUsingBlock:^(NSNumber  * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
                    NSInteger userIndex = key.intValue;
                    
                    if (NSLocationInRange(userIndex, self.lastRange) || (userIndex < lastIndex && userIndex + obj.length > lastIndex)) {
                        
                    }else if (userIndex >= lastIndex) {
                        userIndex = userIndex + index;
                        [result setObject:obj forKey:@(userIndex)];
                    // 包含的情况
                    }else{
                        [result setObject:obj forKey:@(userIndex)];
                    }
                }];

                self.dict = result;
                
                [self.dict setObject:name forKey:@(self.lastRange.location)];

                self.lastRange = changeRange;

                // 修改高亮字段
                [self.textView.textStorage removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, self.textView.text.length)];
                [self.dict enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
                    [self.textView.textStorage addAttributes:@{NSForegroundColorAttributeName:UIColor.redColor} range:NSMakeRange(key.intValue,obj.length)];
                }];
            }
        };
    }
    
    return YES;;
}

- (void)textViewDidChange:(UITextView *)textView{
    
    
    UITextRange *selectedRange = [textView markedTextRange];
       //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    //如果在变化中是高亮部分在变，就不要计算字符了
    if (selectedRange && pos) {
        // 还需要计算内容光标变化位置
        [self changeTextIndex];
        return;
    }
    NSRange selection = textView.selectedRange;
    NSInteger realLength = textView.text.length; //实际总长度
    NSString *headText = [textView.text substringToIndex:selection.location]; //光标前的文本
    NSString *tailText = [textView.text substringFromIndex:selection.location];//光标后的文本
    NSInteger restLength = 20 - tailText.length; //光标后允许输入的文本长度
    if (realLength > 20) {
        NSRange rangeIndex = [headText rangeOfComposedCharacterSequenceAtIndex:restLength];
        restLength = rangeIndex.length == 1?restLength:restLength-1;
        NSString *subHeadText = [headText substringToIndex:restLength];
        textView.text = [subHeadText stringByAppendingString:tailText];
        [textView setSelectedRange:NSMakeRange(restLength, 0)];
    }
    [self changeTextIndex];
    
}

- (void)changeTextIndex{
    // 获取光标的位置
    NSRange currentRange = self.textView.selectedRange;
    // 结算两点光标的位置之差
    NSInteger index = currentRange.location - NSMaxRange(self.lastRange);
    // 结果放入字典保存
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    // 基础
    NSInteger lastIndex = index<0?currentRange.location:self.lastRange.location;
    // 遍历字典中光标的位置是否需要进行移位或者取消高亮
    [self.dict enumerateKeysAndObjectsUsingBlock:^(NSNumber  * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
        NSInteger userIndex = key.intValue;
        if (userIndex >= lastIndex) {
            userIndex = userIndex + index;
            [result setObject:obj forKey:@(userIndex)];
        // 包含的情况
        }else if (userIndex < lastIndex && userIndex + obj.length > lastIndex){

        // 其他
        }else{
            [result setObject:obj forKey:@(userIndex)];
        }
    }];
    self.dict = result;
    self.lastRange = currentRange;
    // 修改高亮字段
    [self.textView.textStorage removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, self.textView.text.length)];
    [self.dict enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
        [self.textView.textStorage addAttributes:@{NSForegroundColorAttributeName:UIColor.redColor} range:NSMakeRange(key.intValue,obj.length)];
    }];
}

@end
